<template>
  <div class="page-wrapper">
    <c-box class="item-1" :title="'电量采集图(万kw.h)'">
      <div class="item-1-wrapper">
        <div id="echarts-2" class="echarts"></div>
        <div id="echarts-3" class="echarts"></div>
      </div>
    </c-box>
    <c-box class="item-2" :title="selected.year + '年' + (selected.month || '') + '电费分布及走势图(万元)'">
      <div id="echarts-1" class="echarts"></div>
    </c-box>
    <c-box class="item-3" :title="selected.year + '年最大需-容量电费对比'">
      <div id="echarts-4" class="echarts"></div>
    </c-box>
    <c-box class="item-4" :title="selected.year + '年节省电费(万元)'">
      <div id="echarts-5" class="echarts"></div>
    </c-box>
  </div>
</template>

<script>
import {
  getPowerForm,
  getElectCollection,
  getElectDistr,
  getElectCycle,
  getElectCapa,
  getElectForm,
  getElectPrice
} from "@/api/power.js";
import {
  toWanKwH,
  getMonthDay,
  getLastMonth,
  getLastDayOfMonth
} from "@/utils";
import echarts from "echarts";
import CBox from "@/components/PageCard";
import {
  colors,
  color,
  activeColor,
  color1,
  activeColor1,
  textColor,
  title,
  legend,
  grid
} from "@/utils/echarts";

const now = new Date();
const curDate = getLastDayOfMonth(getLastMonth(now));
export default {
  name: 'Composition',
  components: { CBox },
  data() {
    return {
      echarts1: null,
      echarts2: null,
      echarts3: null,
      echarts4: null,
      powers: null,
      capaPower: {},
      trendFee: {},
      selected: {
        year: curDate.getFullYear()
      },
      collects: [],
      powerFee: [],
      electCycle: null
    };
  },
  computed: {
    comId() {
      return this.$store.getters.comId;
    }
  },
  async mounted() {
    this.echarts1 = echarts.init(document.getElementById("echarts-1"));
    this.echarts2 = echarts.init(document.getElementById("echarts-2"));
    this.echarts3 = echarts.init(document.getElementById("echarts-3"));
    this.echarts4 = echarts.init(document.getElementById("echarts-4"));
    this.echarts5 = echarts.init(document.getElementById("echarts-5"));
    try {
      const res = await getElectDistr(this.comId);
      this.powers = res.data;
      if (this.powers instanceof Object) {
        const year = this.powers.elecYear[0];
        if (year instanceof Object) {
          this.$set(this.selected, "year", year.yearVal);
        }
      }
      this.setOption1();
      this.setOption2();
      this.echarts2.on("click", async p => {
        if (p.seriesIndex === 0) {
          this.selected = { year: p.name };
        } else if (p.seriesIndex === 1) {
          this.selected = { year: p.data.year, month: p.name };
        } else {
          this.selected = {
            year: p.data.year,
            month: p.data.month
          };
        }
        this.setOption1();
        this.setOption2();
        this.setOption3();
        this.setOption4();
      });
      this.setOption3();
      this.setOption4();
    } catch (error) {
      this.$message.error("加载数据失败!");
    }
  },
  methods: {
    async setOption1() {
      let _data = [];
      const data1 = [],
        data2 = [],
        data3 = [],
        data4 = [],
        total = [],
        xData = [],
        year = this.selected.year,
        month = this.selected.month ? parseInt(this.selected.month) : "",
        key = year + "-" + month;
      if (this.trendFee[key]) {
        _data = this.trendFee[key];
      } else {
        const post = {
          id: this.comId,
          year,
          month
        };
        const res = await this.$axios.post("/eng/lad/electTrend", post);
        _data = res.data;
        this.$set(this.trendFee, key, _data);
      }
      if (!month) {
        for (let i = 1; i <= 12; i++) {
          xData.push(i + "月");
          const a = _data.filter(e => parseInt(e.monthVal) === i)[0];
          if (a) {
            data1.push((a.jianefees / 10000).toFixed(2));
            data2.push((a.fengefees / 10000).toFixed(2));
            data3.push((a.pingefees / 10000).toFixed(2));
            data4.push((a.guefees / 10000).toFixed(2));
            total.push((a.totalefees / 10000).toFixed(2));
          } else {
            data1.push(null);
            data2.push(null);
            data3.push(null);
            data4.push(null);
            total.push(null);
          }
        }
      } else {
        const n = getMonthDay(key);
        for (let i = 1; i <= n; i++) {
          xData.push(i);
          const a = _data.filter(e => parseInt(e.dayVal) === i)[0];
          if (a) {
            data1.push(toWanKwH(a.jianefees));
            data2.push(toWanKwH(a.fengefees));
            data3.push(toWanKwH(a.pingefees));
            data4.push(toWanKwH(a.guefees));
            total.push(toWanKwH(a.totalefees));
          } else {
            data1.push(null);
            data2.push(null);
            data3.push(null);
            data4.push(null);
            total.push(null);
          }
        }
      }
      const option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          }
        },
        legend: {
          data: ["尖电费", "峰电费", "平电费", "谷电费", "总电费"],
          top: "2%",
          ...legend
        },
        grid: {
          ...grid,
          top: 40
        },
        xAxis: {
          type: "category",
          data: xData,
          axisLine: {
            lineStyle: {
              color: textColor
            }
          },
          axisTick: { show: false }
        },
        yAxis: {
          type: "value",
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: textColor
            }
          },
          axisTick: { show: false }
        },
        series: [
          {
            name: "尖电费",
            type: "bar",
            stack: "powerfee",
            barCategoryGap: "50%",
            data: data1
          },
          {
            name: "峰电费",
            type: "bar",
            stack: "powerfee",
            barCategoryGap: "50%",
            data: data2
          },
          {
            name: "平电费",
            type: "bar",
            stack: "powerfee",
            barCategoryGap: "50%",
            data: data3
          },
          {
            name: "谷电费",
            type: "bar",
            stack: "powerfee",
            barCategoryGap: "50%",
            data: data4
          },
          {
            name: "总电费",
            type: "line",
            data: total,
            // barGap: "-100%",
            // barCategoryGap: "50%",
            z: 3
          }
        ]
      };
      this.echarts1.setOption(option);
    },
    setOption2() {
      let data1 = [];
      const data2 = [],
        data3 = [];
      const color = color,
        activeColor = activeColor;
      data1 = this.powers.elecYear.map(e => {
        return {
          name: e.yearVal,
          value: (e.totalPower / 10000).toFixed(2)
          // itemStyle: {
          //   color: this.selected.year === e.yearVal ? activeColor : color
          // }
        };
      });

      this.powers.elecMonth.forEach(e => {
        const r = {
          name: e.monthVal + "月",
          year: e.yearVal,
          value: (e.totalPower / 10000).toFixed(2),
          itemStyle: {
            // color:
            //   this.selected.month === e.monthVal + "月" ||
            //   (!this.selected.month && this.selected.year === e.yearVal)
            //     ? activeColor
            //     : color
          }
        };
        data2.push(r);
        const t = [
          {
            name: "尖",
            value: toWanKwH(e.jianPower),
            year: e.yearVal,
            month: e.monthVal + "月",
            itemStyle: {
              // color:
              //   this.selected.month === e.monthVal + "月" ||
              //   (!this.selected.month && this.selected.year === e.yearVal)
              //     ? activeColor
              //     : color
            }
          },
          {
            name: "峰",
            value: (e.fengPower / 10000).toFixed(2),
            year: e.yearVal,
            month: e.monthVal + "月",
            itemStyle: {
              // color:
              //   this.selected.month === e.monthVal + "月" ||
              //   (!this.selected.month && this.selected.year === e.yearVal)
              //     ? activeColor
              //     : color
            }
          },
          {
            name: "平",
            value: toWanKwH(e.pingPower),
            year: e.yearVal,
            month: e.monthVal + "月",
            itemStyle: {
              // color:
              //   this.selected.month === e.monthVal + "月" ||
              //   (!this.selected.month && this.selected.year === e.yearVal)
              //     ? activeColor
              //     : color
            }
          },
          {
            name: "谷",
            value: toWanKwH(e.guPower),
            year: e.yearVal,
            month: e.monthVal + "月",
            itemStyle: {
              // color:
              //   this.selected.month === e.monthVal + "月" ||
              //   (!this.selected.month && this.selected.year === e.yearVal)
              //     ? activeColor
              //     : color
            }
          }
        ];
        data3.push(...t);
      });

      const option = {
        color: colors,
        tooltip: {},
        title: {
          text: "年、月电量分布图(万kw.h)",
          textStyle: {
            fontSize: 14,
            align: "center",
            fontWeight: "normal"
          },
          x: "center",
          y: "1%"
        },
        grid,
        legend: {
          show: false,
          orient: "vertical",
          top: "middle",
          right: "5%",
          textStyle: {
            color: "#f2f2f2",
            fontSize: 14
          },
          icon: "roundRect"
        },
        series: [
          // 主要展示层的
          {
            radius: ["25%", "45%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            // itemStyle: {
            //   normal: {
            //     color: color,
            //     borderColor: "white"
            //   }
            // },
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            name: "年用电量",
            data: data1
          },
          {
            radius: ["45%", "65%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            name: "月用电量",
            data: data2
          },
          {
            radius: ["65%", "85%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            itemStyle: {
              normal: {
                color: color,
                borderColor: "white"
              }
            },
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            data: data3
          }
        ]
      };
      this.echarts2.setOption(option);
    },
    async setOption3() {
      await this.getElectCollection();
      const data1 = [],
        data2 = [],
        data3 = [],
        title = this.selected.year + "年" + (this.selected.month || "");
      this.collects.forEach(c => {
        let t = 0;
        c.ecectList.forEach(e => {
          const et =
            parseFloat(e.jianPower) +
            parseFloat(e.fengPower) +
            parseFloat(e.pingPower) +
            parseFloat(e.guPower);
          data2.push({
            name: e.transformer,
            value: toWanKwH(et),
            label: {
              formatter: a => {
                return a.name.replace("配变", "").replace("低压进线", "");
              }
            }
          });
          const r = [
            {
              name: "尖",
              value: toWanKwH(e.jianPower)
            },
            {
              name: "峰",
              value: toWanKwH(e.fengPower)
            },
            {
              name: "平",
              value: toWanKwH(e.pingPower)
            },
            {
              name: "谷",
              value: toWanKwH(e.guPower)
            }
          ];
          data3.push(...r);
          t += et;
        });
        data1.push({
          name: c.switchRoom,
          value: toWanKwH(t),
          label: {
            formatter: a => {
              return a.name.replace("配电房", "");
            }
          }
        });
      });
      const option = {
        color: colors,
        tooltip: {},
        title: {
          text: title + "电量采集图(万kw.h)",
          textStyle: {
            fontSize: 14,
            align: "center",
            fontWeight: "normal"
          },
          x: "center",
          y: "1%"
        },
        grid,
        series: [
          // 主要展示层的
          {
            radius: ["25%", "45%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12,
                  color: "#fff"
                }
              }
            },
            name: "年用电量",
            data: data1
          },
          {
            radius: ["45%", "65%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12,
                  color: "#fff"
                }
              }
            },
            name: "月用电量",
            data: data2
          },
          {
            radius: ["65%", "85%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12,
                  color: "#fff"
                }
              }
            },
            data: data3
          }
        ]
      };
      this.echarts3.setOption(option);
    },
    async setOption4() {
      let data = [];
      const data1 = [],
        data2 = [],
        data3 = [];
      if (this.capaPower[this.selected.year]) {
        data = this.capaPower[this.selected.year];
      } else {
        const res = await getElectCapa(this.comId, this.selected.year);
        if (!this.capaPower) {
          this.capaPower = {};
        }
        data = res.data;
        this.$set(this.capaPower, this.selected.year, res.data);
      }
      this.setOption5(data);

      for (let i = 1; i <= 12; i++) {
        const d = data.filter(e => e.monthval === i)[0];
        if (d) {
          data1.push({
            itemStyle: {
              color: this.selected.month === i + "月" ? activeColor : color
            },
            value: toWanKwH(d.maxpowerfee)
          });
          data2.push({
            itemStyle: {
              color: this.selected.month === i + "月" ? activeColor1 : color1
            },
            value: toWanKwH(d.capacityfees)
          });
          data3.push(toWanKwH(d.maxpower));
        } else {
          data1.push(null);
          data2.push(null);
          data3.push(null);
        }
      }
      const option = {
        color: colors,
        textStyle: textColor,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross"
          }
        },
        legend: {
          ...legend
        },
        xAxis: [
          {
            type: "category",
            data: [
              "1月",
              "2月",
              "3月",
              "4月",
              "5月",
              "6月",
              "7月",
              "8月",
              "9月",
              "10月",
              "11月",
              "12月"
            ],
            axisLine: {
              lineStyle: {
                color: textColor
              }
            },
            axisTick: {
              show: false
            },
            axisPointer: {
              type: "shadow",
              label: {
                color: "#fff"
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            name: "万元",
            axisLine: {
              lineStyle: {
                color: textColor
              }
            },
            splitLine: { show: false },
            axisPointer: {
              label: { color: "#fff" }
            }
          },
          {
            type: "value",
            name: "万kw",
            axisLine: {
              lineStyle: {
                color: textColor
              }
            },
            axisPointer: {
              label: { color: "#fff" }
            },
            splitLine: { show: false }
          }
        ],
        series: [
          {
            name: "最大需电费",
            type: "bar",
            label: {
              show: false,
              rotate: 90
            },
            itemStyle: {
              color: color
            },
            data: data1
          },
          {
            name: "容量电费",
            type: "bar",
            label: {
              show: false,
              rotate: 90
              // position: 'top'
            },
            itemStyle: {
              color: color1
            },
            barCategoryGap: "40%",
            data: data2
          },
          {
            name: "最大需",
            type: "line",
            yAxisIndex: 1,
            data: data3
          }
        ]
      };
      this.echarts4.setOption(option);
    },
    async setOption5(_data) {
      const xData = [],
        data = [],
        tt = [];
      for (let i = 1; i <= 12; i++) {
        xData.push(i + "月");
        const a = _data.find(e => e.monthval === i);
        if (a) {
          const t = Math.abs(a.maxpowerfee - a.capacityfees);
          tt.push(t);
          data.push((t / 10000).toFixed(2));
        } else {
          data.push(null);
        }
      }
      let t, total;
      if (tt.length > 1) {
        t = tt.reduce((a, b) => a + b);
        total = (t / 10000).toFixed(2);
      }
      const option = {
        title: {
          text: "总共：" + (total || "-") + "万元",
          ...title,
          top: 0
        },
        color: colors,
        textStyle: {
          color: textColor
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          }
        },
        grid: {
          ...grid,
          top: 50
        },
        xAxis: {
          type: "category",
          data: xData,
          axisLine: {
            lineStyle: {
              color: textColor
            }
          },
          axisTick: {
            show: false
          },
          axisPointer: {
            type: "shadow",
            label: {
              color: "#666"
            }
          }
        },
        yAxis: {
          type: "value",
          name: "万元",
          axisLine: {
            lineStyle: {
              color: textColor
            }
          },
          splitLine: { show: false }
        },
        series: {
          type: "bar",
          label: {
            show: true,
            position: "top"
          },
          barCategoryGap: "50%",
          data: data
        }
      };
      this.echarts5.setOption(option);
    },
    async getElectForm() {
      const res = await getElectForm(
        this.comId,
        this.selected.year,
        this.selected.month
      );
      this.powerFee = res.data;
    },
    async getElectCycle() {
      const res = await getElectCycle(this.comId);
      this.electCycle = res.data;
    },

    dateChange(type) {
      this.curType = type;
      this.getPowerForm(type);
      this.getElectCollection();
      this.handleCurrentChange(this.page.pageIndex);
      this.handleCurrentChange1(this.page1.pageIndex);
    },
    async getElectCollection() {
      const res = await getElectCollection(
        this.comId,
        this.selected.year,
        this.selected.month
      );
      this.collects = res.data;
    },
    async handleCurrentChange(num) {
      const res = await getElectForm(
        this.comId,
        this.dateRang.dateOne,
        this.dateRang.dateTwo,
        num,
        this.page.pageSize
      );
      this.powerFee = res.data.rows;
      this.$set(this.page, "total", res.data.total);
      this.$set(this.page, "pageIndex", num);
    },
    async handleCurrentChange1(num) {
      const res = await getElectPrice(
        this.comId,
        this.dateRang.dateOne,
        this.dateRang.dateTwo,
        num,
        this.page1.pageSize
      );
      this.$set(this.page1, "total", res.data.total);
      this.powerFee1 = res.data.rows;
      this.$set(this.page1, "total", res.data.total);
      this.$set(this.page1, "pageIndex", num);
    },
    async getPowerForm(type) {
      if (type === "year" && !this.input.year) {
        return;
      } else if (type === "month" && !this.input.month) {
        return;
      } else if (type === "date" && !this.input.date) {
        return;
      } else {
        if (this.input.rang.length === 0) {
          return;
        }
      }
      const res = await getPowerForm(
        this.comId,
        this.dateRang.dateOne,
        this.dateRang.dateTwo
      );
      this.value = res.data;
    }
  }
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  position: relative;
  display: grid;
  grid-template-columns: repeat(11, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 10px;
  .item-1 {
    grid-column-start: 1;
    grid-column-end: 7;
    .item-1-wrapper {
      height: 100%;
      width: 100%;
      display: grid;
      grid-template-columns: 1fr 1fr;
    }
  }
  .item-2 {
    grid-column-start: 7;
    grid-column-end: 12;
  }
  .item-3 {
    grid-column-start: 1;
    grid-column-end: 6;
  }
  .item-4 {
    grid-column-start: 6;
    grid-column-end: 12;
  }
}
</style>
